<template>
  <div class="search">
    <el-select v-model="select" placeholder="Select" style="width: 100px;margin-right: 10px;">
      <el-option
        v-for="item in selectList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-input style="width: 200px;margin-right: 10px;"></el-input>
    <el-button type="success" plain @click="search">搜索</el-button>
      <el-button type="primary" plain @click="dialogAddBookVisible = true">添加书籍</el-button>
  </div>
  <div v-if="bookList1.isShow">
  <el-table :data="bookList1.list" border stripe style="width: 100%;height:100%">
    <el-table-column prop="name" label="书名" width="180" />
    <el-table-column prop="editor" label="作者" width="180" />
    <el-table-column prop="category" label="类别" />
    <el-table-column prop="press" label="出版社" />
    <el-table-column prop="left" label="剩余数" />
    <el-table-column label="能否借阅" >
      <template #default="scope">
        <span style="margin-left: 10px">{{
          (scope.row.left > 0) ? "是" : "否"
        }}</span>
      </template>
    </el-table-column>
    <el-table-column width="300">
      <template #default="scope">
        <el-button
          size="small"
          type="primary"
          :disabled="!(scope.row.left > 0)"
          @click="checkClick(scope.$index, scope.row)"
          >查看借阅</el-button>

        <el-button
          size="small"
          type="warning"
          :disabled="!(scope.row.left > 0)"
          @click="editClick(scope.$index, scope.row)"
          >编辑</el-button>
      
        <el-popconfirm 
            title="删除书籍的同时会删除该书的借阅记录！请谨慎操作！"
            confirm-button-text="Yes"
            cancel-button-text="No"
            :icon="InfoFilled"
            icon-color="#626AEF"
            @confirm="confirmDelete(scope.$index, scope.row)"
            @cancel="cancelDelete">
            <template #reference>
            <el-button 
              size="small" 
              type="danger"
              >删除</el-button>
            </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination 
      class="page"
      :total="bookList.length"
      layout="prev, pager, next"
    />
  </div>

    <el-dialog
        v-model="dialogAddBookVisible"
        title="添加书籍"
        width="60%"
        :before-close="handleClose">

          <el-form :model="bookForm">
            <el-form-item label="书名" :label-width="formLabelWidth">
                <el-input v-model="bookForm.name" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="ISBN" :label-width="formLabelWidth">
                <el-input v-model="bookForm.ISBN" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="出版社" :label-width="formLabelWidth">
                <el-input v-model="bookForm.press" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="作者" :label-width="formLabelWidth">
                <el-input v-model="bookForm.editor" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="类别" :label-width="formLabelWidth">
                <el-input v-model="bookForm.category" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="描述1" :label-width="formLabelWidth">
                <el-input v-model="bookForm.attr1" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="描述2" :label-width="formLabelWidth">
                <el-input v-model="bookForm.attr2" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="描述3" :label-width="formLabelWidth">
                <el-input v-model="bookForm.attr3" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="描述4" :label-width="formLabelWidth">
                <el-input v-model="bookForm.attr4" autocomplete="off" clearable/>
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth">
                <el-input-number v-model="bookForm.amount" :min="1"  @change="handleChange" />
            </el-form-item>
            <el-form-item label="剩余量" :label-width="formLabelWidth">
               <el-input-number v-model="bookForm.left" :min="1"  @change="handleChange" />
            </el-form-item>
             <el-form-item label="价格" :label-width="formLabelWidth">
                  <el-input-number v-model="bookForm.price" :precision="2" :step="0.1" :max="10" placeholder="人民币"/>
            </el-form-item>
        </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogAddBookVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmAddBook(bookForm)">
                提交
                </el-button>
            </span>
            </template>
    </el-dialog>

    <el-dialog v-model="dialogEditVisible" title="编辑书籍">
        <el-form :model="form">
            <el-form-item label="书名" :label-width="formLabelWidth">
                <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="ISBN" :label-width="formLabelWidth">
                <el-input v-model="form.ISBN" autocomplete="off" />
            </el-form-item>
            <el-form-item label="出版社" :label-width="formLabelWidth">
                <el-input v-model="form.press" autocomplete="off" />
            </el-form-item>
            <el-form-item label="作者" :label-width="formLabelWidth">
                <el-input v-model="form.editor" autocomplete="off" />
            </el-form-item>
            <el-form-item label="类别" :label-width="formLabelWidth">
                <el-input v-model="form.category" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述1" :label-width="formLabelWidth">
                <el-input v-model="form.attr1" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述2" :label-width="formLabelWidth">
                <el-input v-model="form.attr2" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述3" :label-width="formLabelWidth">
                <el-input v-model="form.attr3" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述4" :label-width="formLabelWidth">
                <el-input v-model="form.attr4" autocomplete="off" />
            </el-form-item>
            <el-form-item label="数量" :label-width="formLabelWidth">
             <el-input-number v-model="form.amount" :min="1" @change="handleChange" />
            </el-form-item>
            <el-form-item label="剩余量" :label-width="formLabelWidth">
               <el-input-number v-model="form.left" :min="1" @change="handleChange" />
            </el-form-item>
             <el-form-item label="价格" :label-width="formLabelWidth">
                <el-input-number v-model="form.price" :precision="2" :step="0.1" :max="10" placeholder="人民币"/>
            </el-form-item>
        </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogEditVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmEdit">
                确定
                </el-button>
            </span>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogHistoryVisible" title="书籍借阅历史" class="abow_dialog" style="height: 80%" width="1200">
            <el-table ref="tableRef" row-key="ISBN" :data="historys" style="width: 100%">
                <el-table-column
                prop="ISBN"
                label="ISBN"
                column-key="ISBN"
                width="150"
                />
                <el-table-column prop="bookname" label="书名"/>
                <el-table-column prop="ReaderID" label="借阅者"/>
                <el-table-column prop="LendDate" label="借书日期" width="300"/>
                <el-table-column prop="ReturnDate" label="还书日期" width="300"/>
                <el-table-column prop="lendNum" label="借阅数量"/>
                <el-table-column prop="isLost" label="丢失"/>
                <el-table-column prop="isReturned" label="已归还"/>
            </el-table>
        </el-dialog>
</template>

<script lang='ts' setup>
import {ref,onBeforeMount,reactive} from 'vue'
import BookService from '../../stores/BookService'
import { ElMessage, ElMessageBox, TableInstance } from 'element-plus'
import { ElNotification } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

//添加书籍
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()

const bookForm = reactive({
  ISBN: '',
  name: 'Hello',
  press: '',
  editor: '',
  category: '',
  attr1: '',
  attr2: '',
  attr3: '',
  attr4: '',
  amount: null,
  left: null,
  price: null,
})
 //添加书籍
const dialogAddBookVisible = ref(false)
const confirmAddBook = async (book) =>{
  dialogAddBookVisible.value = false

  const[err, res] = await BookService.promise_process(BookService.addBook(book))
  if(err){
    console.log(err)
    ElMessageBox.alert('请求服务器失败', '提示', {
             type: 'warning'
    })
  }
  if(res){
   fetchBook()
     ElMessageBox.alert(res.msg, '提示', {
             type: 'success'
    })
  }

}

const bookList = [
  {
    name: "《黎明之剑》",
    auth: "远瞳",
    category: "科幻",
    isBorrow: false,
  },
  {
    name: "《人间失格》",
    auth: "太宰治",
    category: "现实",
    isBorrow: false,
  },
  {
    name: "《呐喊》",
    auth: "鲁迅",
    category: "小说",
    isBorrow: false,
  },
  {
    name: "《鲁滨逊漂流记》",
    auth: "丹尼尔·笛福",
    category: "小说",
    isBorrow: true,
  },
];
const selectList = [
  {
    value: "name",
    label: "书名",
  },
  {
    value: "auth",
    label: "作者",
  },
  {
    value: "category",
    label: "类别",
  },
];
const bookList1 = reactive({
  list : [],
  isShow : false
})
const select = ref('name')



//删除书目
const confirmDelete = async (index, row) => {
    console.log(index, row)
    
    const [err, res] = await BookService.promise_process(BookService.deleteBook(row));
    if(err){
        console.log(err)
          ElMessageBox.alert("请求服务器失败", '提示', {
             type: 'warning'
         })
    }
    if(res){
        console.log(res)
         ElMessageBox.alert(res.msg, '提示', {
             type: 'success'
         })
    }
   fetchBook()
}
const cancelDelete = () => {
}

//编辑书籍信息
const dialogEditVisible = ref(false)

const formLabelWidth = '140px'
let form = reactive({
  ISBN: '',
  amount: '',
  attr1: '',
  attr2: '',
  attr3: '',
  attr4: '',
  category: '',
  editor: '',
  left: 0,
  name: '',
  press: '',
  price: 0
})
const editClick = (index, row) => {
    dialogEditVisible.value = true
    form = row
}
const confirmEdit = async () =>{
    dialogEditVisible.value = false
    const [err, res] = await BookService.promise_process(BookService.editBook(form))
    if(err){
        console.log(err)
       ElMessageBox.alert("请求服务器失败", '提示', {
             type: 'warning'
    })
    }
    if(res){
        console.log(res)
         ElMessageBox.alert(res.msg, '提示', {
             type: 'success'
    })
    }
}

//查看书籍借阅历史
const dialogHistoryVisible = ref(false)
const tableRef = ref<TableInstance>()
let historys = ref(null)

const checkClick = async (index, row) => {
    let isbn = row.ISBN
    //通过isbn码向服务器请求该书的借阅历史
    const [err, res] = await BookService.promise_process(BookService.getLendHistoryByISBN(isbn))
    dialogHistoryVisible.value = true
    if(err){
        console.log(err)
        alert("请求服务器失败")
    }
    if(res){
        console.log(res)
        //alert(res.msg)
        historys = res.data
        console.log(historys)
    }
}

const fetchBook = () =>{
        fetch('http://127.0.0.1:5000/books',{
          method : 'GET',
          mode : 'cors',
          credentials : 'include',
        }).then(response => response.json())
          .then(data => {
            bookList1.list = data.data
            console.log(bookList1.list);
            bookList1.isShow = true
          })
          .catch(err => console.log(err))
}

onBeforeMount(fetchBook)
</script>

<style scoped>
.search{
    margin-top: 20px;
    margin-bottom: 20px;
    margin-left: 20px;
    text-align: left;

}
.page{
    position: absolute;
    left: 50%;
    
}
.el-message {
  z-index: 99999999 !important;
}

</style>
